/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package o2uz;

import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import o2uz.exceptions.NonexistentEntityException;

/**
 *
 * @author tomcat
 */
public class UserJpaController implements Serializable {

    public UserJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(User user) {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            UserRole fkUserRole = user.getFkUserRole();
            if (fkUserRole != null) {
                fkUserRole = em.getReference(fkUserRole.getClass(), fkUserRole.getIdUserRole());
                user.setFkUserRole(fkUserRole);
            }
            Institute fkInstitute = user.getFkInstitute();
            if (fkInstitute != null) {
                fkInstitute = em.getReference(fkInstitute.getClass(), fkInstitute.getIdInstitute());
                user.setFkInstitute(fkInstitute);
            }
            Group1 fkGroup = user.getFkGroup();
            if (fkGroup != null) {
                fkGroup = em.getReference(fkGroup.getClass(), fkGroup.getIdGroup());
                user.setFkGroup(fkGroup);
            }
            em.persist(user);
            if (fkUserRole != null) {
                fkUserRole.getUserCollection().add(user);
                fkUserRole = em.merge(fkUserRole);
            }
            if (fkInstitute != null) {
                fkInstitute.getUserCollection().add(user);
                fkInstitute = em.merge(fkInstitute);
            }
            if (fkGroup != null) {
                fkGroup.getUserCollection().add(user);
                fkGroup = em.merge(fkGroup);
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(User user) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User persistentUser = em.find(User.class, user.getIdUser());
            UserRole fkUserRoleOld = persistentUser.getFkUserRole();
            UserRole fkUserRoleNew = user.getFkUserRole();
            Institute fkInstituteOld = persistentUser.getFkInstitute();
            Institute fkInstituteNew = user.getFkInstitute();
            Group1 fkGroupOld = persistentUser.getFkGroup();
            Group1 fkGroupNew = user.getFkGroup();
            if (fkUserRoleNew != null) {
                fkUserRoleNew = em.getReference(fkUserRoleNew.getClass(), fkUserRoleNew.getIdUserRole());
                user.setFkUserRole(fkUserRoleNew);
            }
            if (fkInstituteNew != null) {
                fkInstituteNew = em.getReference(fkInstituteNew.getClass(), fkInstituteNew.getIdInstitute());
                user.setFkInstitute(fkInstituteNew);
            }
            if (fkGroupNew != null) {
                fkGroupNew = em.getReference(fkGroupNew.getClass(), fkGroupNew.getIdGroup());
                user.setFkGroup(fkGroupNew);
            }
            user = em.merge(user);
            if (fkUserRoleOld != null && !fkUserRoleOld.equals(fkUserRoleNew)) {
                fkUserRoleOld.getUserCollection().remove(user);
                fkUserRoleOld = em.merge(fkUserRoleOld);
            }
            if (fkUserRoleNew != null && !fkUserRoleNew.equals(fkUserRoleOld)) {
                fkUserRoleNew.getUserCollection().add(user);
                fkUserRoleNew = em.merge(fkUserRoleNew);
            }
            if (fkInstituteOld != null && !fkInstituteOld.equals(fkInstituteNew)) {
                fkInstituteOld.getUserCollection().remove(user);
                fkInstituteOld = em.merge(fkInstituteOld);
            }
            if (fkInstituteNew != null && !fkInstituteNew.equals(fkInstituteOld)) {
                fkInstituteNew.getUserCollection().add(user);
                fkInstituteNew = em.merge(fkInstituteNew);
            }
            if (fkGroupOld != null && !fkGroupOld.equals(fkGroupNew)) {
                fkGroupOld.getUserCollection().remove(user);
                fkGroupOld = em.merge(fkGroupOld);
            }
            if (fkGroupNew != null && !fkGroupNew.equals(fkGroupOld)) {
                fkGroupNew.getUserCollection().add(user);
                fkGroupNew = em.merge(fkGroupNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = user.getIdUser();
                if (findUser(id) == null) {
                    throw new NonexistentEntityException("The user with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            User user;
            try {
                user = em.getReference(User.class, id);
                user.getIdUser();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            UserRole fkUserRole = user.getFkUserRole();
            if (fkUserRole != null) {
                fkUserRole.getUserCollection().remove(user);
                fkUserRole = em.merge(fkUserRole);
            }
            Institute fkInstitute = user.getFkInstitute();
            if (fkInstitute != null) {
                fkInstitute.getUserCollection().remove(user);
                fkInstitute = em.merge(fkInstitute);
            }
            Group1 fkGroup = user.getFkGroup();
            if (fkGroup != null) {
                fkGroup.getUserCollection().remove(user);
                fkGroup = em.merge(fkGroup);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<User> findUserEntities() {
        return findUserEntities(true, -1, -1);
    }

    public List<User> findUserEntities(int maxResults, int firstResult) {
        return findUserEntities(false, maxResults, firstResult);
    }

    private List<User> findUserEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(User.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public User findUser(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(User.class, id);
        } finally {
            em.close();
        }
    }

    public int getUserCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<User> rt = cq.from(User.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
